/*
 * download2.h
 *
 *  Created on: May 3, 2011
 *      Author: xrose
 */

#ifndef DOWNLOAD2_H_
#define DOWNLOAD2_H_
#include <string>
#include "incdefault.h"
#include "Url.h"
#include "linkParser.h"
#include "urlCollection.h"
#include "downloader.h"

struct DownlFunctionAttr{
public:
	DownlFunctionAttr():id_thread(0){
		ptr_download = NULL;
	}
	DownlFunctionAttr(downloader *downlPtr, int thrId):id_thread(thrId), ptr_download(downlPtr){
	}
	~DownlFunctionAttr(){
		ptr_download = NULL;
	}

	int id_thread;
	downloader *ptr_download;
};

void* downloadHanle(void *arg){
	cout<<"DEBUG: file:download2.h ...downloadHandle()"<<endl;
	DownlFunctionAttr *dfa = (DownlFunctionAttr*)arg;
	downloader *download = dfa->ptr_download;
	int id = dfa->id_thread;
	cout<<"DEBUG: file:download2.h ...++donwloadHanle():id = "<<id<<endl;
	download->downloadThreadId(id);
	pthread_exit(0);
}

int downloadFile(string url, int thrNum){
	cout<<"DEBUG: file:download2.h ...downloadFile(): url = "<<url<<"thrNum"<<thrNum<<endl;
	downloader download(url, thrNum);
	pthread_t threads[thrNum];
	for(int i = 0; i<thrNum; i++){
		DownlFunctionAttr dfa(&download, i);
		pthread_create(&threads[i], NULL, downloadHanle, (void*)&dfa);
		sleep(1);
	}
	//join thread
	for(int i = 0; i<thrNum; i++){
		pthread_join(threads[i], NULL);
	}
	download.saveFile();
	cout<<"DEBUG: ___downloadFile()"<<endl;
	return 0;
}
void *download_links_hand(void* arg){
	downloader *downl = (downloader*)arg;
	downl->downloadThreadId(0);
	pthread_exit(0);
}
int download_links(string url){
	Url _url(url);
	int threadNum = 1;

	int status = downloadFile(url, threadNum);
	if (status == ERROR){
		return ERROR;
	}

	linkParser link_parser(_url.getHostname(), _url.getIdentifier());
	URLCollection url_coll = link_parser.getLink();
	int threadNumLinks = url_coll.getsize();
	pthread_t threads[threadNumLinks];
	for(int i = 0; i < threadNumLinks; i++){
		downloader downl(url, threadNum);
		if ((pthread_create(&threads[i], NULL, download_links_hand, (void*)&downl)) !=0 ){
			return ERROR;
		}
		sleep(1);
		downl.saveFile();
	}
	// Join threads
	for (int i = 0; i<threadNumLinks; i++)
	{
		pthread_join(threads[i], NULL);
	}
	return SUCCESS;
}


#endif /* DOWNLOAD2_H_ */
